package com.clothing.customization.service.impl;

import com.clothing.customization.service.HomeService;
import com.clothing.customization.repository.*;
import com.clothing.customization.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class HomeServiceImpl implements HomeService {

    @Autowired
    private OrderRepository orderRepository;
    
    @Autowired
    private AppointmentRepository appointmentRepository;
    
    @Autowired
    private DesignWorkRepository designWorkRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private ActivityRepository activityRepository;

    @Override
    @Transactional(readOnly = true)
    public Map<String, Object> getHomeStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 获取订单统计
        long orderCount = orderRepository.countByStatus(1);
        double orderTrend = calculateOrderTrend();
        
        // 获取预约统计
        long appointmentCount = appointmentRepository.countByStatus(0);
        double appointmentTrend = calculateAppointmentTrend();
        
        // 获取收藏统计
        long favoriteCount = userRepository.countUserFavorites();
        double favoriteTrend = calculateFavoriteTrend();
        
        // 获取消息统计
        long messageCount = activityRepository.countUnreadActivities();
        double messageTrend = calculateMessageTrend();
        
        stats.put("orderCount", orderCount);
        stats.put("orderTrend", orderTrend);
        stats.put("appointmentCount", appointmentCount);
        stats.put("appointmentTrend", appointmentTrend);
        stats.put("favoriteCount", favoriteCount);
        stats.put("favoriteTrend", favoriteTrend);
        stats.put("messageCount", messageCount);
        stats.put("messageTrend", messageTrend);
        
        return stats;
    }

    @Override
    @Transactional(readOnly = true)
    public List<Map<String, Object>> getRecentOrders() {
        List<CustomerOrder> orders = orderRepository.findTop4ByOrderByCreateTimeDesc();
        return orders.stream().map(order -> {
            Map<String, Object> map = new HashMap<>();
            map.put("orderNo", order.getOrderNo());
            map.put("productName", order.getProductName());
            map.put("orderTime", order.getCreateTime());
            map.put("status", order.getStatus());
            return map;
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional(readOnly = true)
    public List<Map<String, Object>> getPendingAppointments() {
        List<Appointment> appointments = appointmentRepository.findTop4ByStatusOrderByAppointmentTimeAsc(0);
        return appointments.stream().map(appointment -> {
            Map<String, Object> map = new HashMap<>();
            map.put("appointmentNo", appointment.getAppointmentNo());
            map.put("type", appointment.getType());
            map.put("designerName", appointment.getDesigner().getRealName());
            map.put("appointmentTime", appointment.getAppointmentTime());
            return map;
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional(readOnly = true)
    public List<Map<String, Object>> getRecommendDesigns() {
        List<DesignWork> designs = designWorkRepository.findTop5ByOrderByLikeCountDesc();
        return designs.stream().map(design -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", design.getId());
            map.put("title", design.getTitle());
            map.put("designerName", design.getDesigner().getRealName());
            map.put("coverUrl", design.getCoverUrl());
            map.put("likeCount", design.getLikeCount());
            return map;
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional(readOnly = true)
    public List<Map<String, Object>> getRecentActivities() {
        List<Activity> activities = activityRepository.findTop5ByOrderByCreateTimeDesc();
        return activities.stream().map(activity -> {
            Map<String, Object> map = new HashMap<>();
            map.put("content", activity.getContent());
            map.put("time", activity.getCreateTime());
            map.put("type", activity.getType());
            map.put("color", getActivityColor(activity.getType()));
            return map;
        }).collect(Collectors.toList());
    }
    
    // 计算订单趋势
    private double calculateOrderTrend() {
        long currentCount = orderRepository.countByCreateTimeBetween(
            getStartOfDay(), new Date()
        );
        long previousCount = orderRepository.countByCreateTimeBetween(
            getStartOfPreviousDay(), getStartOfDay()
        );
        return calculateTrendPercentage(previousCount, currentCount);
    }
    
    // 计算预约趋势
    private double calculateAppointmentTrend() {
        long currentCount = appointmentRepository.countByCreateTimeBetween(
            getStartOfDay(), new Date()
        );
        long previousCount = appointmentRepository.countByCreateTimeBetween(
            getStartOfPreviousDay(), getStartOfDay()
        );
        return calculateTrendPercentage(previousCount, currentCount);
    }
    
    // 计算收藏趋势
    private double calculateFavoriteTrend() {
        long currentCount = userRepository.countFavoritesByTimeBetween(
            getStartOfDay(), new Date()
        );
        long previousCount = userRepository.countFavoritesByTimeBetween(
            getStartOfPreviousDay(), getStartOfDay()
        );
        return calculateTrendPercentage(previousCount, currentCount);
    }
    
    // 计算消息趋势
    private double calculateMessageTrend() {
        long currentCount = activityRepository.countByCreateTimeBetween(
            getStartOfDay(), new Date()
        );
        long previousCount = activityRepository.countByCreateTimeBetween(
            getStartOfPreviousDay(), getStartOfDay()
        );
        return calculateTrendPercentage(previousCount, currentCount);
    }
    
    // 计算趋势百分比
    private double calculateTrendPercentage(long previous, long current) {
        if (previous == 0) return current > 0 ? 100 : 0;
        return ((double) (current - previous) / previous) * 100;
    }
    
    // 获取今天开始时间
    private Date getStartOfDay() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }
    
    // 获取昨天开始时间
    private Date getStartOfPreviousDay() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }
    
    // 获取活动颜色
    private String getActivityColor(String type) {
        Map<String, String> colorMap = new HashMap<>();
        colorMap.put("ORDER", "#409EFF");
        colorMap.put("APPOINTMENT", "#67C23A");
        colorMap.put("DESIGN", "#E6A23C");
        colorMap.put("SYSTEM", "#909399");
        return colorMap.getOrDefault(type, "#909399");
    }
} 